
package com.android.formula.common;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.util.Log;

import com.android.formula.R;
import com.android.formula.utils.LogUtils;

public class DialogsManager {
    protected static final int ERROR_DIALOG_NONE = 0;

    protected static final int ERROR_DIALOG_NORMAL = 1;

    protected static final int ERROR_DIALOG_RETRY = 2;

    private final String TAG = this.getClass().toString();

    /**
     * the AlertDialog that is created from [mDialogMessageBuilder].
     */
    protected Dialog mConfirmDialog;

    /**
     * A dialog showing a progress indicator and an optional text message or
     * view.
     */
    private ProgressDialog mProgressDialog;

    /**
     * Base context
     */
    private Context mContext;

    /**
     * Activity
     */
    private Activity mActivity;

    /**
     * the flag to know that this activity has been destroyed.
     */
    private boolean mIsActivityDestroy = false;

    /**
     * constructor
     * 
     * @param context
     */
    public DialogsManager(Activity activity) {
        mContext = activity.getBaseContext();
        mActivity = activity;
    }

    /************************************* Progress Dialog **************************************/

    /**
     * set mIsActivityDestroy
     * 
     * @param isDestroy
     */
    public void setActivityDestroy(boolean isDestroy) {
        mIsActivityDestroy = isDestroy;
    }

    /**
     * Show progress dialog to notify when the thread is running.
     * 
     * @param msgResId id of the message.
     */
    public void showProgress(int msgResId) {
        showProgress(msgResId, null);
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }

    /**
     * Show progress dialog to notify when the thread is running.
     * 
     * @param msgResId id of the message.
     * @param keyListener used to receive listener when user press on an button
     *            of dialog.
     */
    public void showProgress(int msgResId, DialogInterface.OnKeyListener keyListener) {
        if (mActivity == null || (mProgressDialog != null && mProgressDialog.isShowing())) {
            return;
        }
        LogUtils.logInfo(TAG, "showProgress " + mActivity.getClass());

        mProgressDialog = new ProgressDialog(mActivity);
        mProgressDialog.setIndeterminate(true);
        if (msgResId != 0) {
            mProgressDialog.setMessage(mContext.getResources().getString(msgResId));
        }

        if (keyListener != null) {
            mProgressDialog.setOnKeyListener(keyListener);
        } else {
            mProgressDialog.setCancelable(false);
        }

        // check is showing confirm dialog or not.
        if (!mIsActivityDestroy) {
            try {
                mProgressDialog.show();
            } catch (Exception e) {
                LogUtils.logError(TAG, Log.getStackTraceString(e));
                // WindowManager$BadTokenException will be caught and the app
                // would not display
                // the 'Force Close' message
            }
        }
    }

    /**
     * Dismiss the progress dialog that are showing.
     */
    public void dismissProgress() {
        if (mProgressDialog != null) {
            LogUtils.logInfo(TAG, "dismissProgress");
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    /**************************************** Confirm Dialog **************************************/

    /**
     * show dialog with the UI of ecogazoo pet dialog
     * 
     * @param title : The title of dialog. This title textView will be GONE if
     *            the title is 0
     * @param mgs : The content message of dialog
     * @param negativeTextId : <br>
     *            The text of negative button. Background of negativeButtonText
     *            is: d_button_c_background.xml. <br>
     *            This negative button will be GONE if the negativeButtonText is
     *            0
     * @param negativeButtonListener : <br>
     *            The listener of negative button. If negativeButtonListener is
     *            null, we will set the listener as default, just to dismiss
     *            dialog
     * @param positiveTextId : <br>
     *            The text of positive button. Background of positiveButtonText
     *            is: d_button_b_background.xml. <br>
     *            This positive button will be GONE if the positiveButtonText is
     *            0
     * @param positiveButtonListener : <br>
     *            The listener of positive button. If positiveButtonListener is
     *            null, we will set the listener as default, just to dismiss
     *            dialog
     * @param isCancelable : <bR>
     *            The flag to allow cancel dialog by press back key.
     */
    public final void showConfirmDialog(int title, int mgs, int negativeTextId,
            DialogInterface.OnClickListener negativeButtonListener, int positiveTextId,
            DialogInterface.OnClickListener positiveButtonListener, boolean isCancelable) {

        String tempTitle = title <= 0 ? null : mContext.getString(title);
        String tempMgs = mgs <= 0 ? null : mContext.getString(mgs);
        String tempNegative = negativeTextId <= 0 ? null : mContext.getString(negativeTextId);
        String tempPositive = positiveTextId <= 0 ? null : mContext.getString(positiveTextId);

        if (tempPositive != null && positiveButtonListener == null) {
            positiveButtonListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            };
        }

        if (tempNegative != null && negativeButtonListener == null) {
            negativeButtonListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            };
        }

        showConfirmDialog(tempTitle, tempMgs, tempNegative, negativeButtonListener, tempPositive,
                positiveButtonListener, isCancelable);
    }

    /**
     * show dialog with the UI of ecogazoo pet dialog
     * 
     * @param title : The title of dialog. This title textView will be GONE if
     *            the title is null
     * @param mgs : The content message of dialog
     * @param negativeButtonText : <br>
     *            The text of negative button. Background of negativeButtonText
     *            is: d_button_c_background.xml. <br>
     *            This negative button will be GONE if the negativeButtonText is
     *            null
     * @param negativeButtonListener : <br>
     *            The listener of negative button. If negativeButtonListener is
     *            null, we will set the listener as default, just to dismiss
     *            dialog
     * @param positiveButtonText : <br>
     *            The text of positive button. Background of positiveButtonText
     *            is: d_button_b_background.xml. <br>
     *            This positive button will be GONE if the positiveButtonText is
     *            null
     * @param positiveButtonListener : <br>
     *            The listener of positive button. If positiveButtonListener is
     *            null, we will set the listener as default, just to dismiss
     *            dialog
     * @param isCancelable : <bR>
     *            The flag to allow cancel dialog by press back key.
     */
    public final void showConfirmDialog(String title, String mgs, String negativeButtonText,
            DialogInterface.OnClickListener negativeButtonListener, String positiveButtonText,
            DialogInterface.OnClickListener positiveButtonListener, boolean isCancelable) {
        if (mContext == null) {
            return;
        }
        if (mConfirmDialog != null) {
            mConfirmDialog.dismiss();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        if (!TextUtils.isEmpty(title)) {
            builder.setTitle(title);
        }
        builder.setMessage(mgs);
        if (!TextUtils.isEmpty(positiveButtonText)) {
            builder.setPositiveButton(positiveButtonText, positiveButtonListener);
        }
        if (!TextUtils.isEmpty(negativeButtonText)) {
            builder.setNegativeButton(negativeButtonText, negativeButtonListener);
        }
        builder.setCancelable(isCancelable);

        mConfirmDialog = builder.create();
        // #45570: disable cancel when touch out side.
        mConfirmDialog.setCanceledOnTouchOutside(false);
        try {
            mConfirmDialog.show();
        } catch (Exception e) {
            // WindowManager$BadTokenException will be caught and the app
            // would not display
            // the 'Force Close' message
            LogUtils.logError(TAG, Log.getStackTraceString(e));
        }
    }

    /**
     * Dismiss the confirm dialog.
     */
    public final void dismissConfirmDialog() {
        if (mConfirmDialog != null) {
            mConfirmDialog.dismiss();
        }
    }

    /**
     * Check the confirm dialog is showing or not.
     * 
     * @return true if the confirm dialog is showing.
     */
    public boolean isShowingConfirmDialog() {
        if (mConfirmDialog != null && mConfirmDialog.isShowing()) {
            return true;
        }
        return false;
    }

    /**************************************** Error Dialog **************************************/

    /**
     * Show dialog error with a button (not apply retry flow) if listener null
     * -> auto dismiss when click button
     * 
     * @param title
     * @param msg
     * @param btn
     * @param closeButtonClickListener
     * @return
     */
    public final int showErrorDialog(String title, String msg, String btn,
            DialogInterface.OnClickListener closeButtonClickListener) {

        if (mContext == null) {
            return ERROR_DIALOG_NONE;
        }
        int errrorDialogType = ERROR_DIALOG_NORMAL;
        boolean isEnableBackKey = false;
        if (closeButtonClickListener == null) {
            closeButtonClickListener = new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dismissConfirmDialog();
                }
            };
        }
        if (TextUtils.isEmpty(btn)) {
            btn = mContext.getString(R.string.btn_ok_text);
        }
        showConfirmDialog(title, msg, btn, closeButtonClickListener, null, null, isEnableBackKey);
        return errrorDialogType;
    }

    public final int showErrorDialog(int titleId, int msgId, int captionBtnId,
            DialogInterface.OnClickListener closeButtonClickListener) {
        if (mContext == null) {
            return ERROR_DIALOG_NONE;
        }
        String title = titleId <= 0 ? null : mContext.getString(titleId);
        String msg = msgId <= 0 ? null : mContext.getString(msgId);
        String btn = captionBtnId <= 0 ? null : mContext.getString(captionBtnId);
        showErrorDialog(title, msg, btn, closeButtonClickListener);
        return ERROR_DIALOG_NONE;
    }

    /********************************* Common ***************************************/
    /**
     * dismiss all dialogs
     */
    public void dismissDialogs() {
        dismissConfirmDialog();
        dismissProgress();
    }

    public void showProgressFromBackground(final int msgId) {
        if (mActivity == null) {
            return;
        }
        mActivity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                showProgress(msgId);
            }
        });
    }

    public void dismissProgressFromBackground() {
        if (mActivity == null) {
            return;
        }
        mActivity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                dismissProgress();
            }
        });
    }

}
